package com.dsg.kf.socket.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.dsg.kf.common.util.DateUtil;
import com.dsg.kf.socket.context.MessageConcurrentLinkedQueue;
import com.dsg.kf.socket.mapper.MessageLogMapper;
import com.dsg.kf.socket.message.MessageBase;

/**
 * spring 容器启动完毕后 将立即自动执行此方法
 * 消费消息 持久化到db里
 * 
 * @author pacy.pan
 *
 */
@Service
public class InnerDbMessageService implements ApplicationListener<ContextRefreshedEvent> {

	@Autowired
	private MessageLogMapper messageLogMapper;

	/**
	 * 异步启动此service 方法
	 * 
	 * @param arg0
	 */
	@Async
	public void onApplicationEvent(ContextRefreshedEvent arg0) {
		ExecutorService executor = Executors.newFixedThreadPool(1);
		Thread thread = null;
		for (int i = 0; i < 1; i++) {
			thread = new Thread(new ReceThread());
			thread.setDaemon(true);// 守护线程
			executor.execute(thread);
		}
		try {
			executor.shutdown();
			executor.awaitTermination(500, TimeUnit.MILLISECONDS);
		} catch (InterruptedException ignored) {
			ignored.printStackTrace();
		}
	}

	private class ReceThread implements Runnable {
		@Override
		public void run() {
			List<MessageBase> messageArray = new ArrayList<MessageBase>();
			while (true) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				}
				MessageBase message = MessageConcurrentLinkedQueue.pollMessageQueue();
				if (message != null) {
					messageArray.add(message);
				}
				if (messageArray.size() >= 10) {
					messageLogMapper.batchInsertMessageLog(messageArray,
							DateUtil.formatSimple(DateUtil.yyyyMM, new Date()));
					messageArray.clear();
				}
			}
		}
	}
}
